package com.rzj.book.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rzj.book.en.Category;
import com.rzj.book.service.ICategoryService;
import com.rzj.book.utils.PageResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController{

    @Autowired
    private ICategoryService categoryService;
    
	@RequestMapping("/category_list")
	public void getlist(Integer page,Integer rows,Category category)
	{
	 try {
		 PageResult<Category> categoryList = categoryService.getListByCategort(page,rows,category);
		 write(JSON.toJSONString(categoryList));
	} catch (Exception e) {
		ajaxReturn(false, "未知错误");
		e.printStackTrace();
	}
  }

	@RequestMapping("/getCategory")
	public void getCategory(Integer id)
	{
		Category category = null;
		try {
			category =categoryService.getCategoryById(id);
			write(JSON.toJSONString(category));
		} catch (Exception e) {
			ajaxReturn(false, "未知错误");
			e.printStackTrace();
		}
	}

	@RequestMapping("/getCategoryCommbox")
	public void getCategoryCommbox(){
		try {
		    List<Category> list = categoryService.getCategoryCommbox();
			JSONArray jsonArray = new JSONArray();
			jsonArray.add(new JSONObject().element("id","").element("text","请选择"));
			for(Category item:list){
             jsonArray.add(new JSONObject().element("id",item.getId()).element("text",item.getName()));
			}
			write(JSON.toJSONString(jsonArray));
		} catch (Exception e) {
			ajaxReturn(false, "未知错误");
			e.printStackTrace();
		}
	}

	@RequestMapping("/persistenceCategory")
	public void persistenceCategory(Category category)
	{
		try {
			if(category.getId() != null){
				categoryService.updateById(category);
			}else {
				categoryService.addCategory(category);
			}
			ajaxReturn(true, "商品分类数据更新成功");
		} catch (Exception e) {
			ajaxReturn(false, "商品分类数据更新失败");
			e.printStackTrace();
		}
	}

	@RequestMapping("/deleteCategory")
	public void deleteCategory(Integer id)
	{
		try {
			categoryService.deleteCategory(id);
			ajaxReturn(true, "商品分类删除成功");
		} catch (Exception e) {
			ajaxReturn(false, "商品分类删除失败");
			e.printStackTrace();
		}
	}

	@RequestMapping("/excelCategory")
	public void excelCategory(Category category)
	{
		try {
			HttpServletResponse response = getResponse();
			response.setHeader("Content-Disposition", "attachment;filename="+new String("分类.xls".getBytes(),"ISO-8859-1"));
			categoryService.excelCategory(response.getOutputStream(), category);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
